package com.situ.web.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.situ.web.entity.Student;
import com.situ.web.entity.Teacher;
import com.situ.web.util.JDBCUtil;

public class TeacherDao {

	public int getTotalCount() {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		int count = 0;
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select count(*) from teacher";
			preparedStatement = connection.prepareStatement(sql);
			System.out.println(preparedStatement);
			resultSet = preparedStatement.executeQuery();
			// 查询数量只有一行一列，这个while循环只会执行一次
			while (resultSet.next()) {
				count = resultSet.getInt(1);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		return count;
	}

	public List<Teacher> findByPage(int offset, int pageSize) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList<Teacher> list = new ArrayList<Teacher>();
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select id,name,age,salary from teacher limit ?,?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, offset);
			preparedStatement.setInt(2, pageSize);
			// 打印preparedStatement可以打印出发送的sql语句
			System.out.println(preparedStatement);
			resultSet = preparedStatement.executeQuery();
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				//int id = resultSet.getInt(1);
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				int salary = resultSet.getInt("salary");
				Teacher teacher = new Teacher(id, name, age, salary);
				list.add(teacher);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, resultSet);
		}
		
		for (Teacher teacher : list) {
			System.out.println(teacher);
		}
		
		return list;
	}

}
